<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            font-size: 18px;
        }

        .box {
            height: 2000px;
        }

        .div {
            width: 20px;
            height: 100px;
            background-color: pink;
            border: solid black 1px;
            position: fixed;
            bottom: 30px;
            right: 20px;
        }
    </style>
</head>

<body>
    <div class="box"></div>
    <div class="div">回到顶部</div>
    <script>
        var btn = document.querySelector(".div")
        window.onscroll = function () {
            var num = document.documentElement.scrollTop
            btn.onclick = function () {
                var timer = setInterval(function () {
                    num -= 1;
                    console.log(num);
                    document.documentElement.scrollTop = num
                    if (num < 0) {
                        clearInterval(timer)
                    }
                }, 1);
            }
        }

    </script>
</body>

</html>